#!/usr/bin/perl

##### Copyright (c) 2009 Wade Nelson
##### See the file COPYING for copying permission.

use strict;
use warnings;
use CGI qw(:standard);

### Variable Declaration
my $postDir = "../hbdocs";
my $siteName = "My Really Cool Site";

### Blog post sort order
sub sortParam {
    # sort by oldest first: $a cmp $b;
    # sort by newest first: $b cmp $a;
    $a cmp $b;
}

### Read Blog Post Files
my %blogPosts;
opendir(DOCDIR, "$postDir") or die("Unable to open blog post directory!");
while (defined(my $file = readdir(DOCDIR))) {
    if ($file =~ m/.txt$/i) {
        my %postData = &fileParser("$postDir/$file");
        $blogPosts{"$postData{DATE}_$postData{TIME}"} = \%postData;
    }
}
closedir(DOCDIR);

### Build Web Page (HTML)
print header(), "\n";
print start_html( -title=>"$siteName" ), "\n";
print '<table border="0" width="95%" align="center" cellspacing="16">', "\n";
print '<tr valign="top">', "\n";
print '<th align="left" colspan="2">', "\n";
print h1("$siteName"), "\n";
print '</th>', "\n";
print '</tr>', "\n";
print '<tr valign="top">', "\n";
print '<td width="25%" align="left">', "\n";
print strong("Table of Contents:");
print '<ul>', "\n";
foreach my $key (sort sortParam keys(%blogPosts)) {
    print '<li>', "$blogPosts{$key}->{DATE}", br;
    print a({-href=>"#$blogPosts{$key}->{DATE}_$blogPosts{$key}->{TIME}"}, 
        "$blogPosts{$key}->{TITLE}"), '</li>', "\n"
}
print '</ul>', "\n";
print '</td>', "\n";
print '<td width="75%" align="left">', "\n";
foreach my $key (sort sortParam keys(%blogPosts)) {
    print a({-name=>"$blogPosts{$key}->{DATE}_$blogPosts{$key}->{TIME}"}), "\n";
    print strong("$blogPosts{$key}->{TITLE}"), br, "\n";
    print "$blogPosts{$key}->{DATE}, $blogPosts{$key}->{TIME}\n", br, "\n";
    print "by $blogPosts{$key}->{AUTHOR}\n", br, br, "\n";
    print "$blogPosts{$key}->{POST}\n", br, "\n";
    print br, hr, br, "\n";
}
print '</td>', "\n";
print '</tr>', "\n";
print '</table>', "\n";
print end_html(), "\n";




### Parses blog post files.
### Accepts a file as an argument, returns a hash of the file contents.
sub fileParser {
    my $file = $_[0];
    my %blogPost;
    open(FILE, "$file") or die("fileParser: Unable to open file!\n");
    until ( eof(FILE) ) {
        chomp($file = <FILE>);
        if ( $file =~ m/\s*(POST):\s*(.*)/ ) {
            my $postText = $2;
            until ( eof(FILE) ) {
                $postText = $postText . ($file = <FILE>);
            }
            $blogPost{'POST'} = "$postText";
        }
        elsif ( $file =~ m/\s*(\w*):\s*(.*)/ ) {
            $blogPost{"$1"} = "$2";
        }
    }
    close(FILE);
    return %blogPost;
}